<template>
  <a-card title="查看房户信息" style="width: 300px;pointer-events: all;">
    <span style="margin-right: 20px;">楼栋选择:</span>
    <a-select ref="select" v-model:value="selectBuild" style="width: 120px" :options="buildsOption"
      @change="handleChange"></a-select>
  </a-card>
</template>

<script setup>
import * as Cesium from 'cesium'
import { ref, onMounted,onUnmounted } from 'vue'
import { getBuild, getOneHouseInfo, getHouse } from '../api/api'
import { useMapData } from '@/store'
import * as turf from '@turf/turf'
import SimpleLabel from '../cesiumTools/Popup/Popup'


const mapStore = useMapData()
// 获取viewer
const viewer = mapStore.Viewer
const selectBuild = ref('')
const buildsOption = ref([])
// 存储所有生成的primitive
const primPrimitives = []
const colors = [
  "#99CCCC",
  "#66FF66",
  "#FF6666",
  "#00CCFF",
  "#00FF33",
  "#CC0000",
  "#CC00CC",
  "#CCFF00",
  "#0000FF",
];
const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
let sceneEvent

// 渲染下拉列表
onMounted(async () => {
  const buildInfo = await getBuild()
  if (buildInfo.code === 200) {
    buildsOption.value = buildInfo.data.map(item => {
      return {
        label: item.name,
        value: item.id,
        polygon: item.polygon
      }
    })
    // 初始化点击事件
    initHandler()
  }
})

// 清除气泡框，事件，pirmitive等
onUnmounted(()=>{

})

// 修改下拉列表，需要得到每一户的信息，并且渲染classifictionPrimitive
const handleChange = async (e) => {
  const target = buildsOption.value.find(item => item.value === e)
  if (target) {
    // 获取到楼栋的多边形范围
    const { polygon, label } = target
    // 得到多边形中心点，让视角跳转过去
    const center = turf.center(polygon)
    // 将视角飞跃到模型中心
    viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(
        ...center.geometry.coordinates,
        300
      )
    })
    // 不走分页，查询全部住户的polygon信息
    const param = {
      id: e, noPage: 1
    }
    const res = await getHouse(param)
    if (res.code === 200) {
      const { data } = res
      data.forEach((item,index) => {
        // 获取到楼栋的多边形范围
        const { polygon, minHeight, maxHeight, id } = item
        // 按照第一节的逻辑，渲染primitive
        const coordinates = polygon.coordinates[0].reduce((a, b) => a.concat(b), [])
        const cartesian = new Cesium.Cartesian3.fromDegreesArray(coordinates)
        const geometryInstance = new Cesium.GeometryInstance({
          id: id,
          geometry: new Cesium.PolygonGeometry({
            polygonHierarchy: new Cesium.PolygonHierarchy(cartesian),
            height: minHeight,
            extrudedHeight: maxHeight
          }),
          attributes: {
            color: Cesium.ColorGeometryInstanceAttribute.fromColor(
              new Cesium.Color.fromCssColorString(colors[id % 9]).withAlpha(0.3)
            )
          }
        })
        const primitive = new Cesium.ClassificationPrimitive({
          geometryInstances: geometryInstance,
          classificationType: Cesium.ClassificationType.CESIUM_3D_TILE
        })
        primPrimitives.push(primitive)
        viewer.scene.primitives.add(primitive)
      })
    }
  }
}

const popup=new SimpleLabel(viewer,{
  offset:[205,180]
})
const renderPopup=(houseInfo,cartesian)=>{
  // 将之前的气泡框清除
  popup.removeMarker()
  popup.changePosition(cartesian)
  popup.addLabel(houseInfo)
}

// 之前点击的pickFeature
let lastPick
// 初始化点击事件
const initHandler = () => {
  sceneEvent = async (e) => {
    const cartesian=viewer.scene.pickPosition(e.position)
    let pick = viewer.scene.pick(e.position)
    // 如果点击到的是我们刚刚生成的primitive，才触发逻辑
    if (pick.id) {
      const {data} = await getOneHouseInfo({ id: pick.id })
      // 渲染气泡框
      renderPopup(data,cartesian)

      // 点击将颜色还原
      if(lastPick && lastPick.id){
        const lastAttrib=lastPick.primitive.getGeometryInstanceAttributes(lastPick.id)
        lastAttrib.color=new Cesium.Color.fromCssColorString(colors[id % 9]).withAlpha(0.3)
      }

      // 将点击到的primitive设置为黄色
      const attributes = pick.primitive.getGeometryInstanceAttributes(pick.id)
      attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.YELLOW.withAlpha(0.88));
    }
  }
  handler.setInputAction(sceneEvent, Cesium.ScreenSpaceEventType.LEFT_CLICK)
}
</script>
<style scoped></style>